package com.example.onlineeducation.ui.mine

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.view.View
import androidx.activity.ComponentActivity
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import com.example.onlineeducation.adapter.QuestionDetailAdapter
import com.example.onlineeducation.base.BaseActivity
import com.example.onlineeducation.data.constant.ExamConstants
import com.example.onlineeducation.data.constant.QuestionType
import com.example.onlineeducation.data.entity.ExamAnswerEntity
import com.example.onlineeducation.databinding.ExamResultAnswerItemBinding
import com.example.onlineeducation.databinding.ExamResultDetailActivityBinding
import com.example.onlineeducation.ui.online.OnlineExaminationAc
import com.example.onlineeducation.utils.YcTimeUtils
import com.example.onlineeducation.viewmodel.ExamResultDetailVM
import com.yc.jetpacklib.extension.ycInitLinearLayoutManage
import com.yc.jetpacklib.extension.ycIsNotEmpty
import com.yc.jetpacklib.extension.ycToNoEmpty
import com.yc.jetpacklib.net.doSuccess
import com.yc.jetpacklib.recycleView.YcRecyclerViewAdapter
import com.yc.jetpacklib.utils.YcTime
import java.util.*


/*
* 考试结果详情
* */
@SuppressLint("SetTextI18n")
class ExamResultDetailActivity : BaseActivity<ExamResultDetailActivityBinding>(ExamResultDetailActivityBinding::inflate) {
    private val mViewModel: ExamResultDetailVM by ycViewModels()
    private var mExamLogId: String? = null
    private var mExamId: String? = null
    private var mExamTotalTime: Int = 0
    private var mExamOverTime: String? = null
    private var mIsExamRecordList = false

    companion object {
        private const val KEY_EXAM_LOG_ID = "key_exam_log_id"
        private const val KEY_EXAM_EXAM_ID = "key_exam_exam_id"
        private const val KEY_EXAM_NAME = "key_exam_name"
        private const val KEY_EXAM_TOTAL_TIME = "key_exam_total_time"
        private const val KEY_EXAM_OVER_TIME = "key_exam_over_time"
        private const val KEY_IS_EXAM_RECORD_LIST = "key_is_exam_record_list"//是从考试记录列表来
        const val KEY_IS_REANSWER = "key_is_reanswer"//再答一次

        /*
        * 从考试记录列表来
        * */
        fun newInstanceExamRecord(context: Context, examLogId: String, examId: String?, examName: String, time: Int?, overTime: String?) {
            val intent = Intent(context, ExamResultDetailActivity::class.java).apply {
                putExtra(KEY_EXAM_LOG_ID, examLogId)
                putExtra(KEY_EXAM_EXAM_ID, examId)
                putExtra(KEY_EXAM_NAME, examName)
                putExtra(KEY_EXAM_TOTAL_TIME, time)
                putExtra(KEY_EXAM_OVER_TIME, overTime)
                putExtra(KEY_IS_EXAM_RECORD_LIST, true)
            }
            context.startActivity(intent)
        }

        fun newInstanceExamResult(context: Context, examLogId: String, examName: String, launcher: ActivityResultLauncher<Intent>) {
            val intent = Intent(context, ExamResultDetailActivity::class.java).apply {
                putExtra(KEY_EXAM_LOG_ID, examLogId)
                putExtra(KEY_EXAM_NAME, examName)
                putExtra(KEY_IS_EXAM_RECORD_LIST, false)
            }
            launcher.launch(intent)
        }

        @JvmStatic
        inline fun getLauncher(activity: ComponentActivity, crossinline block: (isReanswer: Boolean) -> Unit): ActivityResultLauncher<Intent> {
            return activity.registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
                if (it.resultCode == RESULT_OK && it.data != null) {
                    val isReanswer = it.data?.getBooleanExtra(KEY_IS_REANSWER, false)!!
                    block.invoke(isReanswer)
                }
            }
        }
    }

    private val mAnswerResultAdapter by YcRecyclerViewAdapter.ycLazyInitApply<ExamAnswerEntity, ExamResultAnswerItemBinding>(
        ExamResultAnswerItemBinding::inflate
    ) {
        mOnUpdate2 = { position, data ->
            tvQuestionNum.text = (position + 1).toString()
            ivQuestionResult.setImageResource(QuestionType.showAnswerResultIcon(data.isRight))
        }
    }

    private val mQuestionDetailAdapter by lazy {
        QuestionDetailAdapter()
    }


    override fun ExamResultDetailActivityBinding.initView() {
        val mExamName = intent.getStringExtra(KEY_EXAM_NAME) ?: "安全学习考试"
        mIsExamRecordList = intent.getBooleanExtra(KEY_IS_EXAM_RECORD_LIST, false)
        mExamLogId = intent.getStringExtra(KEY_EXAM_LOG_ID)
        if (mIsExamRecordList) {
            mExamId = intent.getStringExtra(KEY_EXAM_EXAM_ID)
            mExamTotalTime = intent.getIntExtra(KEY_EXAM_TOTAL_TIME, 0)
            mExamOverTime = intent.getStringExtra(KEY_EXAM_OVER_TIME)
        }
        actionbarLayout.setTitle(mExamName, leftClick = { goBack() })
        btnReAnswer.setOnClickListener {
            if (mIsExamRecordList) {
                if (mExamId.ycIsNotEmpty() && mExamTotalTime != 0 && mExamOverTime.ycIsNotEmpty()
                    && YcTimeUtils.compareSmaller(YcTime.dateToString(Date(), YcTime.FORMAT_TIME_SECOND), mExamOverTime.ycToNoEmpty())
                ) {
                    OnlineExaminationAc.newInstance(this@ExamResultDetailActivity, mExamId, mExamName, mExamTotalTime, mExamOverTime!!)
                    finish()
                } else {
                    mDialog.setMsg("考试已结束").setSingleBtnText("确定").showSingle()
                }
            } else {
                val intent = Intent()
                intent.putExtra(KEY_IS_REANSWER, true)
                setResult(RESULT_OK, intent)
                finish()
            }
        }
        btnBack.setOnClickListener {
            goBack()
        }

        rvAnswerResult.apply {
            adapter = mAnswerResultAdapter
        }
        rvQuestionDetail.apply {
            adapter = mQuestionDetailAdapter
            ycInitLinearLayoutManage()
        }

        mViewModel.mExamResultDetail.observe {
            it.doSuccess { item ->
                ivExamResult.setImageResource(ExamConstants.showExamResultDetailIcon(item.isPass))
                tvExamResult.text = ExamConstants.showExamResultDetailText(item.isPass)
                tvQuestionTotal.text = item.questionTotal
                tvCorrectRate.text = item.correctRate
                if (item.answerInfo.ycIsNotEmpty()) {
                    mAnswerResultAdapter.addAllData(item.answerInfo)
                    mQuestionDetailAdapter.addAllData(item.answerInfo)
                    rvAnswerResult.visibility = View.VISIBLE
                    groupWrongQuestion.visibility = View.VISIBLE
                } else {
                    rvAnswerResult.visibility = View.GONE
                    groupWrongQuestion.visibility = View.GONE
                }

            }.ycShowNetError()
        }
        getData()
    }

    override fun onBackPressed() {
        goBack()
        super.onBackPressed()
    }


    private fun goBack() {
        if (!mIsExamRecordList) {
            val intent = Intent()
            intent.putExtra(KEY_IS_REANSWER, false)
            setResult(RESULT_OK, intent)
        }
        finish()
    }

    private fun getData() {
        mViewModel.getExamResultDetail(mExamLogId!!)
    }
}